package net.ib.mtalk.network.task;

import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.SuggestionId;
import net.ib.mntalk.protocol.Common.SuggestionIdSliceRange;
import net.ib.mntalk.protocol.Common.SuggestionInfo;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.GetBuddyChangesRes;
import net.ib.mntalk.protocol.Session.GetSuggestionsReq;
import net.ib.mntalk.protocol.Session.GetSuggestionsRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.SuggestionDatabaseHelper;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.ui.buddy.suggestion.BuddySuggestionListActivity;
import net.ib.mtalk.ui.buddy.talk.BuddyTalkListActivity;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.NotifyingAsyncQueryHandler;

public class GetSuggestionsTask extends AsyncNetTask {
	
	private GetSuggestionsReq getSuggestionsReq;
	private long version;

	public GetSuggestionsTask(Context _context, Handler _uiHandler, GetSuggestionsReq getSuggestionsReq, long version) {
		super(_context, _uiHandler);
		this.getSuggestionsReq = getSuggestionsReq;
		this.version = version;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(getSuggestionsReq)
			.setMethodId(Session.Suggestion.GetSuggestions)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject, Object receivedObject) {
		MTalkLogWriter.d("GetSuggestionsTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		GetSuggestionsRes getSuggestionsRes = (GetSuggestionsRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("GetSuggestionsTask ResponseCode : " + getSuggestionsRes.getResponseCode());
		
		if(getSuggestionsRes.getResponseCode() == Common.SUCCESS){
			SuggestionDatabaseHelper.insertSuggestions(mContext, mUiHandler, getSuggestionsRes);
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_SUGGESTIONS_SUCCESS);
			msg.obj = getSuggestionsRes.getSuggestionInfoCount();
			mUiHandler.sendMessageAtFrontOfQueue(msg);
			GlobalPreferences.setSuggestionVersion(version);
		} else {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_SUGGESTIONS_FAIL));
		}

	}

}
